<template>
	<view class="tabContent" :style="{marginTop:$u.addUnit(44 + $u.sys().statusBarHeight,'px'),}">
		<u-navbar style="z-index: 99;" :fixed="true" :safeAreaInsetTop="true">
			<view class="u-nav-slot" slot="left">
				<view class="comboSelect">
					<uni-data-select v-model="selectedCombo" :formatJob="{text:'ModuleName',value:'ModuleID'}"
						:localdata="comboList" :clear="false" iconColor="#fff" @change="changeCombo"></uni-data-select>
				</view>
			</view>
			<view class="u-nav-slot" slot="right">
				<view class="boardSelect" @click="openBaseScreen('看板')">
					<text class="text">{{selectedBoard.boardTitle}}</text>
					<uni-icons fontFamily="CustomFontPlatform" :size="14" color="#fff">{{'\ue605'}}</uni-icons>
				</view>
			</view>
		</u-navbar>

		<view class="subcontent">
			<!-- 看板内容 -->
			<component :is="selectedBoard.boardName" ref="myComponent" :key="componentKey"></component>
		</view>
	</view>
</template>

<script>
	// ERP 看板
	import Sale from '../../commonPage/kanban/erp/sale.vue';
	import Purchase from '../../commonPage/kanban/erp/purchase.vue';
	import Warehouse from '../../commonPage/kanban/erp/warehouse.vue';
	import Finance from '../../commonPage/kanban/erp/finance.vue';
	// 小工单 看板
	import Ticket1 from '../../commonPage/kanban/ticket-1.vue';
	// qms 看板
	import Qms1 from '../../commonPage/kanban/qms-1.vue';

	import layerFun from '@/common/comFun/layerFun.js';
	var layer = layerFun;
	export default {
		components: {
			Sale,
			Purchase,
			Warehouse,
			Finance,
			Ticket1,
			Qms1,
		},

		data() {
			return {
				modules: [], // 当前用户已开通模块				
				selectedCombo: -1, // 当前所选版本
				comboList: [], // 版本列表
				boardList: [], // 看板数据源
				selectedBoard: {
					boardID: 0,
					boardName: '',
					boardTitle: ''
				}, // 当前选中看板
				componentKey: 0,
			}
		},
		created: function() {
			let that = this;
			that.getModule();
		},
		mounted() {
			var that = this;
			uni.$on('Home_Choice', function(ret) {
				const dataCopy = JSON.parse(JSON.stringify(ret.data));
				switch (ret.type) {
					case '看板':
						that.selectedBoard.boardID = dataCopy.boardID;
						that.selectedBoard.boardName = dataCopy.boardName;
						that.selectedBoard.boardTitle = dataCopy.boardTitle;
						that.changeKanBan(that.selectedBoard);
						break;
					default:
						break;
				}
			});


			uni.$on("allowToNavgate", function() {
				that.initAPPModule()
			})
		},
		methods: {

			// 获取产品版本下属模块(APP)
			getModule() {
				let that = this;
				// console.log(this.$store.state.UserInfo.Business);
				that.Request.request('SelectActivatedModule', {
						AccountID: this.$store.state.UserInfo.Business
					}, function(res) {
						that.comboList = res.data.ds;

						let selectedComboInfo = {};
						if (uni.getStorageSync('selectedComboInfo')) {
							// 判断是否存在选中套餐的记录
							let oldSelectedComboInfo = JSON.parse(uni.getStorageSync('selectedComboInfo'))

							let findData = that.comboList.find(item => item.ModuleID == oldSelectedComboInfo.ModuleID);
							if (!that.$utils.isEmpty(findData)) {
								// 于历史记录相匹配
								selectedComboInfo = that.$utils.deepClone(findData);
								that.selectedCombo = selectedComboInfo.ModuleID;
							} else {
								// 不匹配
								selectedComboInfo = that.comboList[0];
								that.selectedCombo = that.comboList[0].ModuleID;
							}
							// 
						} else {
							selectedComboInfo = that.comboList[0];
							that.selectedCombo = that.comboList[0].ModuleID;
						}
						// 持久化记录一下
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'appConfigInfo.selectedComboInfo',
							data: selectedComboInfo,
							StorageName: 'selectedComboInfo',
							StorageData: JSON.stringify(selectedComboInfo)
						});

						// that.selectedCombo = that.comboList[0].ModuleID;
						// 获取当前版本下所有APP菜单
						that.getAllMenuData(that.selectedCombo, 1);
						// 获取当前版本看板列表
						that.getKanBanList();
					}, function(err) {}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 获取所有菜单数据
			getAllMenuData(moduleID, option) {
				let that = this;
				that.$utils.showLoading("正在初始化...")

				that.Request.request('platform_getAppModule', {
						UserID: this.$store.state.UserInfo.UserID,
						ModuleID: moduleID,
						AccountID: this.$store.state.UserInfo.Business
					}, function(res) {
						if (res.data.ds.length) {
							const modules = res.data.ds;
							const pages = res.data.ds1;
							const pagesByModule = new Map();

							// 预处理阶段：初始化选中状态并建立模块-页面映射
							pages.forEach(item => {
								// 简化布尔值赋值
								item.IsChecked = !!item.IsShortcut;

								// 建立模块ID到页面的映射
								if (!pagesByModule.has(item.APPType)) {
									pagesByModule.set(item.APPType, []);
								}
								pagesByModule.get(item.APPType).push(item);
							});

							// 主处理阶段：遍历模块
							modules.forEach(module => {
								// 获取当前模块相关页面（O(1)时间复杂度）
								const modulePages = pagesByModule.get(module.ModuleID) || [];

								// 构建树形结构（使用Map优化去重）
								const treeTypeMap = new Map();
								modulePages.forEach(page => {
									if (!page.IsTabbar) {
										const key = page.TreeType;
										if (!treeTypeMap.has(key)) {
											treeTypeMap.set(key, {
												treeType: key,
												treeTypeName: page.TreeTypeName,
												pages: []
											});
										}
										treeTypeMap.get(key).pages.push(page);
									}
								});

								// 构建最终数据结构
								module.shortcuts = modulePages.filter(p => p.IsShortcut);
								module.treeTypes = Array.from(treeTypeMap.values());
								module.authPages = modulePages;
							});

							that.modules = modules;
							that.$store.commit('ChangeAndSetStateData', {
								Name1: 'appConfigInfo.APPModules',
								data: modules,
							});

							// 异步初始化优化
							if (option === 1) {
								let ActiveModuleStartType = that.$store.state.appConfigInfo.ActiveModuleStartType;
								// 判断是否开机自启
								if (ActiveModuleStartType && process.env.NODE_ENV == 'development') {
									setTimeout(() => {
										that.initAPPModule();
									}, 1000);
								} else {
									that.$utils.hideLoading();
								}



							} else {
								that.$utils.hideLoading();
							}

							// 权限配置处理
							const unPermissionConfig = res.data.ds2 || [];
							that.$store.commit('ChangeAndSetStateData', {
								Name1: 'appConfigInfo.unPermissionConfig',
								data: unPermissionConfig,
							});
						} else {
							that.$utils.hideLoading();
							that.modules = [];
							that.$store.commit('ChangeAndSetStateData', {
								Name1: 'appConfigInfo.APPModules',
								data: [],
							});
						}


						// 强制刷新优化（使用唯一key替代递增计数器）
						that.componentKey = Date.now();

						uni.$emit('refreshCenter', {});

					}, function(err) {
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'appConfigInfo.APPModules',
							data: [],
						});
						that.$utils.hideLoading();
					}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 获取用户APP看板(平台首页)
			getKanBanList() {
				let that = this;
				that.Request.request('PlatForm_SelectKaanBan', {
						UserID: this.$store.state.UserInfo.UserID,
						KanBanType: 2 // 移动看板
					}, function(res) {
						let data = res.data.ds;
						that.boardList = data.map(item => ({
							boardID: item.KanBanID,
							boardName: item.Path.substring(item.Path.lastIndexOf('/') + 1),
							boardTitle: item.KanBanName
						}))
						that.initKanBan();
					}, function(err) {
						console.log(err);
					}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 初始化看板
			initKanBan() {
				// 获取缓存并解析
				const cachedBoardStr = uni.getStorageSync('ActiveBoard');
				const cachedBoard = cachedBoardStr ? JSON.parse(cachedBoardStr) : null;

				// 初始化选中看板
				let selectedBoard = null;

				if (this.boardList.length) {
					// 优先使用缓存中的看板（如果存在且有效）
					const targetBoard = this.boardList.find(
						board => board.boardID === cachedBoard?.boardID
					);

					selectedBoard = targetBoard ? {
						...targetBoard
					} : {
						...this.boardList[0]
					};
				}

				// 更新状态（包含空列表保护）
				if (selectedBoard) {
					this.selectedBoard = selectedBoard;
					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'ActiveBoard',
						data: this.selectedBoard,
						StorageName: 'ActiveBoard',
						StorageData: JSON.stringify(this.selectedBoard)
					});
				}
			},

			// 切换看板
			changeKanBan(board) {
				// console.log(board);
				let that = this;
				that.$store.commit('ChangeAndSetStateData', {
					Name1: 'ActiveBoard',
					data: board,
					StorageName: 'ActiveBoard',
					StorageData: JSON.stringify(board)
				});
			},

			organizeByTreeTypeName(arr, ds1Map) {
				// 创建一个映射来按TreeType分组数据  
				const groupedData = {};

				arr.forEach((item) => {
					const treeType = item.TreeType;
					const treeTypeName = item.TreeTypeName; // 用于分组的键  

					if (!(treeTypeName in groupedData)) {
						groupedData[treeTypeName] = {
							TreeType: treeType, // 保留TreeType  
							APPType: item.appType, // 保留APPType
							Node: [],
						};
					}

					// 检查ds1Map中是否有匹配的APPFunID  
					if (ds1Map.has(item.APPFunID)) {
						groupedData[treeTypeName].Node.push({
							...item,
							IconApprove: ds1Map.get(item.APPFunID), // 如果需要，直接添加IconApprove  
						});
					} else {
						groupedData[treeTypeName].Node.push({
							...item,
							IconApprove: []
						});
					}
				});

				// 提取分组后的数据为数组，并可能按某种逻辑排序（这里不排序，因为TreeTypeName已经是分组键）  
				const sortedData = Object.entries(groupedData).map(([treeTypeName, group]) => ({
					TreeTypeName: treeTypeName,
					...group, // 展开分组对象，它包含TreeType, APPType, APPFunID, 和 Node 数组  
				}));

				return sortedData;
			},
			// 初始化模块页面
			initModule(module) {
				let that = this;
				console.log(module);
				this.$utils.showLoading('正在加载模块');

				this.Request.request('getAPPModulePages', {
					UserID: this.$store.state.UserInfo.UserID,
					APPType: module.ModuleID,
				}, (ret) => {
					console.log(ret);
					if (ret.status == 200) {
						const data = ret.data.ds;
						const ds1 = ret.data.ds1;

						// 预先处理ds1，以APPFunID为键，值为对应的数组  
						const ds1Map = new Map(ds1.map(row => [row.APPFunID, [row]]).reduce((acc, [key, val]) => {
							acc.set(key, [...acc.get(key) || [], ...val]);
							return acc;
						}, new Map()));

						let organizedData = that.organizeByTreeTypeName(data, ds1Map);
						organizedData = organizedData.sort((a, b) => a.TreeType - b.TreeType);

						// 这里获取了模块以及页面的权限树，将 IsTabbar 为true的筛选出来，作为底部栏数据

						let TabbarData = organizedData.flatMap(item => item.Node.filter(row => row.IsTabbar)).sort(
							(a, b) => a.APFunCode - b.APFunCode); // 对结果进行排序
						// console.log(TabbarData) 

						uni.removeStorageSync('ModuleInfo_All');
						uni.removeStorageSync('Module_Tabbar');

						// 模块数据持久化 
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'appConfigInfo.ModuleInfo_All',
							data: organizedData,
							StorageName: 'ModuleInfo_All',
							StorageData: JSON.stringify(organizedData),
						});

						// 模块数据持久化 
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'appConfigInfo.Module_Tabbar',
							data: TabbarData,
							StorageName: 'Module_Tabbar',
							StorageData: JSON.stringify(TabbarData),
						});

						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'appConfigInfo.ActiveModule',
							data: module,
							StorageName: 'ActiveModule',
							StorageData: JSON.stringify(module),
						});
						that.$utils.hideLoading();
						let url = '';

						switch (module.ModuleID) {
							case 3: // qms
								uni.navigateTo({
									url: "/st_qms/index/basicPage"
								})
								break;
							case 2:
							case 6:
							case 10:
							case 12:
							case 13:
								let homePage = module.authPages.find(item => item.IsHomepage);
								if (homePage && homePage != undefined) {
									url = homePage.AP_Link; // 设置首页路径
									uni.navigateTo({
										url: url
									})
								} else {
									uni.showToast({
										icon: 'none',
										title: '当前应用未设置首页!'
									})
								}
								break;
							default:
								console.log(module);
								url = '/commonPage/Module/index' + '?moduleID=' + module.ModuleID + '&index=0';
								console.log(url);
								uni.navigateTo({
									url: url,
									success: (ret) => {
										console.log(ret);
									},
									fail(err) {
										console.log(err);
									}
								})
								break;
						}

					}
				}, (err) => {
					console.log(err)
					// 处理错误  
				});
			},

			// 进入上次APP模块
			initAPPModule() {
				let str = uni.getStorageSync('ActiveModule');
				if (str) {
					let module = JSON.parse(str); // 上次选中APP模块
					this.initModule(module);
				} else {
					this.$utils.hideLoading();
				}
			},

			// 切换版本
			changeCombo(e) {
				console.log(e);
				let that = this;
				that.$store.commit('ChangeAndSetStateData', {
					Name1: 'appConfigInfo.ActiveModule',
					data: null
				});
				uni.removeStorageSync('ActiveModule');

				let selectedComboInfo = that.comboList.find(item => item.ModuleID == e)

				that.$store.commit('ChangeAndSetStateData', {
					Name1: 'appConfigInfo.selectedComboInfo',
					data: selectedComboInfo,
					StorageName: 'selectedComboInfo',
					StorageData: JSON.stringify(selectedComboInfo)
				});


				// 重新获取菜单
				that.getAllMenuData(e, 2);
				// 获取当前版本看板列表
				that.getKanBanList();
			},

			// 基础选择页面
			openBaseScreen(str) {
				let obj = {};
				let url = '/commonPage/Tool/baseScreen?select=1';

				if (str == '看板') {
					obj = {
						allowClear: false,
						cmd: '',
						type: str,
						ListeningName: 'Home_Choice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							showText: 'boardTitle', //查询结果显示的字段
							ChoiceDataKey: 'boardName',
							ChoiceDataData: this.selectedBoard.boardName
						},
						param: {
							data: this.boardList
						}
					}
				}

				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'BaseScreenParm',
					data: obj
				})

				uni.navigateTo({
					url: url
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	$h-padding: 5px;
	$v-padding: 10px;
	$radius: 5px;

	.comboSelect {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
		font-weight: 500;
		width: 185px;
		border-radius: $radius;

		::v-deep .uni-stat-box {
			background-color: transparent !important;
		}
	}

	.boardSelect {
		display: flex;
		align-items: center;
		margin-left: 15px;
		padding: 0 10px;
		height: 35px;
		font-size: 16px;
		font-weight: 500;
		background: rgba(0, 0, 0, .03);
		border-radius: $radius;

		.text {
			color: #fff;
			font-size: 14px;
			margin-right: 5px
		}
	}

	// 版本选择下拉
	.comboSelect ::v-deep .uni-select__input-text {
		font-size: 14px;
		color: #fff;
		background-color: transparent !important;
	}

	.comboSelect ::v-deep .uni-select {
		border: none;
		background-color: transparent !important;
	}

	.tabContent {
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
		padding: $v-padding $h-padding 0;
		// padding-left: $h-padding;
		// padding-right: $h-padding;

		.head {
			position: fixed;
			left: 0;
			top: 0;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			padding: calc(50px + #{$v-padding}) $h-padding $v-padding $h-padding;
			z-index: 2;
			width: 100vw;
			height: 150px;
			background-color: $main-background-color;

			&-top {
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;

				&-left {
					display: flex;
					align-items: center;
					width: 350rpx;
					color: #fff;

					&-text {
						font-size: 32rpx;
						margin-right: 10rpx;
					}
				}
			}

			&-bottom {
				width: 100%;
				margin-top: $v-padding;
			}
		}


		.subcontent {
			display: flex;
			flex-direction: column;
			// padding: calc(50px + env(safe-area-inset-top) + #{$v-padding}) $h-padding $v-padding $h-padding;

			.commonBox {
				display: flex;
				flex-direction: column;
				padding: $v-padding $h-padding;
				background-color: #ffffff;
				margin-bottom: $v-padding;
				border-radius: 15rpx;

				&-title {
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding: 0 $h-padding $v-padding $h-padding;

					&-left {
						display: flex;
						justify-content: flex-start;
						align-items: center;
						width: 150rpx;
					}

					&-right {
						display: flex;
						justify-content: flex-end;
						align-items: center;
						width: 100rpx;
					}
				}

				&-content {
					display: flex;
					flex-direction: column;
				}
			}
		}
	}

	.grid-text {
		font-size: 14px;
		color: #909399;
		padding: 10rpx 0 20rpx 0rpx;
		/* #ifndef APP-PLUS */
		box-sizing: border-box;
		/* #endif */
	}

	.shortcut {
		display: flex;
		flex-direction: column;
		height: 80vh;

		&-content {
			display: flex;
			flex: 1;
			padding: $v-padding $h-padding;
			background-color: #f7f7f7;

			.left_wrap {
				display: flex;
				flex-direction: column;
				width: 180rpx;

				.leftItem {
					display: flex;
					justify-content: center;
					align-items: center;
					height: 60rpx;
				}

				.leftItem.on {
					background-color: $main-background-color;
					color: #ffffff;
				}
			}

			.right_wrap {
				display: flex;
				flex-direction: column;
				flex: 1;

				.rightItem {
					display: flex;
					justify-content: flex-start;
					align-items: center;
					font-size: 28rpx;
					margin-left: $h-padding;
				}

				.rightItem.on {
					background-color: $main-background-color;
					color: #ffffff;
				}
			}
		}

		&-bottom {
			display: flex;
			justify-content: center;
			align-items: center;
			position: fixed;
			width: 100%;
			height: 100rpx;
			padding: $v-padding $h-padding;
			left: 0;
			bottom: calc(100rpx + env(safe-area-inset-bottom) / 2);
		}
	}
</style>